<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>流程图</title>
    <style>
#app{display:flex;display:-webkit-flex;flex-direction:column;-webkit-flex-direction:column;position:absolute;top:0;left:0;width:100%;height:100%}
#header{flex:0 0 auto;-webkit-flex:0 0 auto;line-height:1.3}
#panes{display:flex;display:-webkit-flex;flex:1 1 auto;-webkit-flex:1 1 auto}
#graph{display:flex;display:-webkit-flex;flex-direction:column;-webkit-flex-direction:column}
#options{flex:0 0 auto;-webkit-flex:0 0 auto}
#output{flex:1 1 auto;-webkit-flex:1 1 auto;position:relative;overflow:auto}
#editor{border-right:1px solid #ccc}
#header{background:#eee;border-bottom:1px solid #ccc;padding:6px;text-align:center}
#header b{font-size:18px}
#header input[type=text]{width:6%; min-width:6em;}
#header input[type=text].target{width:24%; min-width:24em;}
#options{background:#eee;border-bottom:1px solid #ccc;padding:4px}
#options label{margin-right:8px}
#options #raw.disabled{opacity:.5}
#output svg{position:absolute;top:0;left:0;width:100%;height:100%}
#output #text{font-size:12px;font-family:monaco,courier,monospace;white-space:pre;position:absolute;top:0;left:0;width:100%;height:100%;overflow:auto}
#output img{display:block;margin:0 auto}
#output.working svg,#output.error svg,#output.working #text,#output.error #text,#output.working img,#output.error img{opacity:.4}
#output.error #error{display:inherit}
#output #error{display:none;position:absolute;top:20px;left:20px;margin-right:20px;background:red;color:white;z-index:1}
.gutter{background-color:#eee;background-repeat:no-repeat;background-position:50%}
.gutter.gutter-horizontal{background-image:url('');cursor:ew-resize}
.split{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;overflow-y:auto;overflow-x:hidden}
.split.split-horizontal,.gutter.gutter-horizontal{height:100%;float:left}
.hide{display: none !important;}
#sub-menu {position: absolute; z-index: 9999; background: white; display: none; max-width:500px; margin-bottom:0;background-color: #EAEEFF;}
#sub-menu ul {margin: 0px;padding:0px;}
#sub-menu ul li {overflow:hidden;border: 1px solid #ddd;border-radius: 5px;}
#sub-menu ul li a, #sub-menu ul li span{display: inline-block;vertical-align: top;}
#sub-menu textarea {max-width:490px;}

    </style>
    <script type="text/javascript" src="../clipboard/clipboard.min.js"></script>
</head>
<body>
<!-- TODO 时序图 https://www.websequencediagrams.com/ -->
<div id="app">
    <div id="header">
        <label id="project_label" title="比如: csm, report4, bi 不确定时可不填">项目 <span class="fa fa-question-circle"></span>:
            <select class="project" name="project">
            </select>
        </label>
        <label id="target_label" title="比如: r12 或 /home/initBoxOffice 或 TimeExtractFundController#findExtractUsersByPage">类名#方法名 或 url <span class="fa fa-question-circle"></span>: <input id="target" name="target" type="text" class="target" /></label>
        <label id="exclude_label" title="只排除叶节点">排除指定包:<input id="exclude" name="exclude" type="text"/></label>
        <label id="showPackage_label">
            <input type="checkbox" name="showPackage">显示包名
        </label>
        <label id="showArgs_label">
            <input type="checkbox" name="showArgs">显示参数
        </label>
        <button class="btn btn-success btn-xs translate depend">查依赖</button>
        <button class="btn btn-success btn-xs translate reference">查引用</button>
        <button class="btn btn-success btn-xs translate all">查依赖引用</button>
        <button class="btn btn-success show_desc btn-xs">查详情</button>
        <button class="btn btn-success download_viz btn-xs">导出为xlsx</button>
        <button class="btn btn-success btn-xs goback">后退</button>
    </div>
    <div id="panes" class="split split-horizontal">
        <div id="editor" class="split"># 语法教程 https://www.jianshu.com/p/e44885a777f0
            digraph G {
            graph[shape="box" fontsize=10 rankdir=LR]
            node[shape="box"  fontsize=10 color="black" bgcolor="red" distortion=.7 gradientangle=90 style=filled]
            edge[fontsize=10 fontcolor="black" color="#003399" style="filled"]

            // VIZ TEMPLATE
            }
        </div>
        <div id="editor_template" style="display:none;"># 语法教程 https://www.jianshu.com/p/e44885a777f0
            digraph G {
            graph[shape="box" fontsize=10 rankdir=LR]
            node[shape="box"  fontsize=10 color="black" bgcolor="red" distortion=.7 gradientangle=90 style=filled]
            edge[fontsize=10 fontcolor="black" color="#003399" style="filled"]

            // VIZ TEMPLATE
            }
        </div>
        <div id="graph" class="split">
            <div id="options">
                <label id="show_source">
                    <input type="checkbox" name="show_source">显示流程图源码
                </label>

                <label id="engine">
                    渲染引擎:
                    <select>
                        <option>circo</option>
                        <option selected>dot</option>
                        <option>fdp</option>
                        <option>neato</option>
                        <option>osage</option>
                        <option>twopi</option>
                    </select>
                </label>

                <label id="rankdir">
                    <input type="checkbox" name="rankdir" >横竖切换
                </label>

                <label id="format">
                    格式:
                    <select>
                        <option selected>svg</option>
                        <option value="png-image-element">png</option>
                        <option>json</option>
                        <option>xdot</option>
                        <option>plain</option>
                        <option>ps</option>
                    </select>
                </label>

                <label id="raw">
                    <input type="checkbox">xml
                </label>
                
                <label id="prompt">
                    <span style="color:#777">提示: 双击任意节点可跳转, 右键任意节点可复制</span>
                </label>
            </div>
            <div id="output">
                <div id="error"></div>
            </div>
        </div>
    </div>

    <div class="contextmenu" id="sub-menu">
        <ul class="list-group">
            <li class="list-group-item">
                <button id="btn_copy_text" class="copy_btn btn btn-default btn-xs" data-clipboard-target="#copy_text">复制当前内容</button>
                <button id="btn_copy_class" class="copy_btn btn btn-default btn-xs hide" data-clipboard-target="#copy_class">复制类名</button>
                <button id="btn_copy_method" class="copy_btn btn btn-default btn-xs hide" data-clipboard-target="#copy_method">复制类名和方法名</button>
                <br/><textarea id="copy_text" rows="15" cols="40">${text}</textarea>
                <span id="copy_field" class="hide">${class}</span>
                <span id="copy_methods" class="hide">${method}</span>
        </ul>
    </div>
</div>

<script src="./bower_components/ace.js"></script>
<script src="./bower_components/viz.js"></script>
<script src="./bower_components/fabric.min.js"></script>
<script src="./bower_components/split.min.js"></script>
<script src="./bower_components/svg-pan-zoom.min.js"></script>
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="../../sybn_common.js"></script>
<script type="text/javascript" src="./viz_template.js"></script>
<link rel="stylesheet" href="../../../css/fontawesome-4.2.0_ie7/4.2.0/css/font-awesome.min.css">

</body>
<script>
var backList = [];
window.onload = function() {
  updateGraph();

  var project = getQueryString("project");
  if (project) {
    $('[name=project]').val(project);
  }
  
  // 显示数据源
  showSelect('../../../api/viz/translate_java_project.json' , $('.project'), project, true);

  var exclude = getQueryString("exclude");
  if (exclude) {
    $('[name=exclude]').val(exclude);
  }

  var showPackage = getQueryString("showPackage");
  if (showPackage == 'true') {
    $('[name=showPackage]').attr( "checked", "checked");
  } else {
    $('[name=showPackage]').attr( "checked", "");
  }

  var showArgs = getQueryString("showArgs");
  if (showArgs == 'true') {
    $('[name=showArgs]').attr( "checked", "checked");
  } else {
    $('[name=showArgs]').attr( "checked", "");
  }

  var target = getQueryString("target");
  if (target) {
    $('[name=target]').val(target);
    backList.push($('#target').val());
    translate();
  }

  $('.CodeMirror').addClass("form-control");
  // 查询
  $('body').on('click', '#header button', function(e){
    if(backList[backList.length-1] != $('#target').val()) {
        backList.push($('#target').val());
    }
    translate(e, this);
  });
  // 横纵转换
  $('body').on('click', '[name=rankdir]', ()=>{
    var s = editor.getValue();
    if ($('[name=rankdir]').is(":checked")){
        s = s.replace("rankdir=LR", "rankdir=TB");
    } else {
        s = s.replace("rankdir=TB", "rankdir=LR");
    }
    editor.setValue(s);
  });
  // 显示/隐藏源码
  $('body').on('click', '[name=show_source]', ()=>{
     toggleSource();
  });
  toggleSource();

  // 查看详情
  $('body').on('click', 'button.show_desc', function(){
	var target = $('[name=target]').val();
	if (target) {
        var url = "/dw-api-core/sql.html?sql=" + encodeURIComponent("SELECT * FROM java_method_callee_info where method_full_name like '%"+target+"%' or url like '%"+target+"'");
        window.open(url, "_blank");
    }
  });

  // 查看详情
  $('body').on('click', 'button.download_viz', function(){
	var target = $('[name=target]').val();
	if (target) {
       downloadViz();
    }
  });

  // 返回
  $('body').on('click', 'button.goback', function(){
    if (backList.length > 1 && backList[backList.length-2]) {
        var v = backList[backList.length-2];
        backList.pop();
		$('[name=target]').val(v);
		translate();
    }
    return false;
  });
  // 实现双击跳转效果
  $('body').on('dblclick', 'g.node', function(x){
    // copyText(x.currentTarget);

    var title = $(x.currentTarget).find("title");
    if (title && title.length==1) {

        var $text = $(x.currentTarget).find("text");
        if ($text.length>1) {
            var target = $text[0].textContent + "#" + $text[1].textContent;
            if (backList[backList.length-1] != target) {
                $('#target').val(target);
                $("button.all").click();
                return false;
            }
        }
        var target = title.text();
        if (backList[backList.length-1] != target) {
            $('#target').val(target);
            $("button.all").click();
        }
    }
    return false;
  });
};

// 显示/隐藏 源码窗口
function toggleSource() {
    if ($('[name=show_source]').is(":checked")){
        $('#editor').show();
        $('.gutter-horizontal').show();
        var $g = $('#graph');
        $g.attr('style', $g.attr('style2'));
    } else {
        $('#editor').hide();
        $('.gutter-horizontal').hide();
        var $g = $('#graph');
        $g.attr('style2', $g.attr('style'));
        $g.attr('style', 'width:100%');
    }
}

// 查询数据
function translate(e, _this) {
	var target = $('[name=target]').val();
	if (!target) {
	  return;
	}
	var project = $('[name=project]').val();
	var exclude = $('[name=exclude]').val();
	var showPackage = $('[name=showPackage]:checked').val();
	showPackage = showPackage ? "true" : "false";
	var showArgs = $('[name=showArgs]:checked').val();
	showArgs = showArgs ? "true" : "false";

	$this = $(_this) || $(this);
	var reference = $this && $this.hasClass("reference");
	var all = $this && $this.hasClass("all");
	var depend = $this && $this.hasClass("depend");
	var action = getQueryString("action");
	var type = (reference?'callee':(all?'all':(depend?'caller':action)));

    var url2 = changeURLPar(window.location.href.toString(), "target", target);
    url2 = changeURLPar(url2, "action", type);
    url2 = changeURLPar(url2, "project", project);
    url2 = changeURLPar(url2, "exclude", exclude);
    url2 = changeURLPar(url2, "showPackage", showPackage);
    url2 = changeURLPar(url2, "showArgs", showArgs);
    window.history.pushState({},0,url2);

	// 防止双击触发单击
	$.ajax({
	     url: "../../../api/viz/translate_java.json",
	     type:'post',
	     dataType:'json',
	     async:true, // 异步请求
	     cache:false,
	     data: {project:project, target:target, type: type, exclude: exclude, showPackage:showPackage, showArgs:showArgs},
	     //执行成功的回调函数
	     success:function(data) {
	      	  if (data.status && data.status >= 400){
	      	    alert(data.message ? "操作失败: " + data.message : "操作失败!");
	      	  } else if (!data.result){
	      	    alert(data.msg ? "操作失败: " + data.msg : "操作失败!");
	      	  } else {
	      	    var s = $("#editor_template").text();
	      	    if ($('[name=rankdir]').is(":checked")){
	      	        s = s.replace("rankdir=LR", "");
	      	    }
	      	    s = s.replace("// VIZ TEMPLATE", data.output);
                editor.setValue(s);
	          }
	     },
	     //执行失败或错误的回调函数
	     error:function(data) {
	         alert("操作失败");
	     }
	});
}

// 查询数据
function downloadViz(e, _this) {
	var target = $('[name=target]').val();
	if (!target) {
	  return;
	}
	var project = $('[name=project]').val();
	var exclude = $('[name=exclude]').val();
	var showPackage = $('[name=showPackage]:checked').val();
	showPackage = showPackage ? "true" : "false";
	var showArgs = $('[name=showArgs]:checked').val();
	showArgs = showArgs ? "true" : "false";

	$this = $(_this) || $(this);
	var reference = $this && $this.hasClass("reference");
	var all = $this && $this.hasClass("all");
	var depend = $this && $this.hasClass("depend");
	var action = getQueryString("action");
	var type = (reference?'callee':(all?'all':(depend?'caller':action)));

    var url = "../../../api/viz/download_translate_java.xlsx";
<!--	var data = {project:project, target:target, type: type, exclude: exclude, showPackage:showPackage, showArgs:showArgs};-->
<!--    openPostWindow(url, data, "_blank")-->
    url += "?project="+encodeURIComponent(project)+"&target="+encodeURIComponent(target)+"&type="+encodeURIComponent(type)+"&exclude="+encodeURIComponent(exclude)+"&showPackage="+showPackage+"&showArgs="+showArgs;
    window.open(url);
}

$(document).ready(function(){
    if ($("#sub-menu").length == 0) {
        return;
    }
    // 开启右键菜单
    $("#sub-menu").hide();
    // 开启粘贴板
    new ClipboardJS('.copy_btn');

    $('#graph').on('contextmenu', 'g.node, g.node text', function(e){
        var text = "";
        var $text = $(this).find("text");
        var $node = $(this);
        if ($text.length == 0) {
            text = $(this).text();
            $node = $(this).closest("g.node");
            // TODO
        } else {
            $text.each(function() {
                if (text != "") {
                    text += "\r\n";
                }
                text += $(this).text();
            });
        }
        $("#sub-menu").show(100)
        $('#sub-menu').css({'top': e.pageY + 'px','left': e.pageX + 'px'});
        $("#copy_text").text(text);
        return false;
    });

    // 单击关闭右键菜单
    $(document).on('click', "#sub-menu textarea, #sub-menu input", function(e) {
        return false;
    });
    $(document).on('click', function(e) {
        var evt = event.srcElement ? event.srcElement : event.target;
        if (evt.id == 'sub-menu') {
            return;
        }
        $('#sub-menu').hide();
    });
});
</script>
</html>
